﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace PKEngine
{
	/// <summary>
	/// Singleton that handles all the keyboard events.
	/// The dispatcher dispatches events to the registered KeybdHandlers.
	/// </summary>
	public class PKKeybdDispatcher
	{
		#region PKKeybdEventType
		private enum PKKeybdEventType
		{
			KeyDown,
			KeyUp,
			KeyMax
		}
		#endregion

		#region Singleton
		private static PKKeybdDispatcher _sharedDispatcher;

		public static PKKeybdDispatcher SharedDispatcher
		{
			get
			{
				if (_sharedDispatcher == null)
				{
					_sharedDispatcher = new PKKeybdDispatcher();
				}
				return _sharedDispatcher;
			}
		}
		#endregion

		#region Private Fields
		List<PKKeybdHandler> keybdHandlers;
		bool locked;
		bool toAdd;
		List<PKKeybdHandler> handlersToAdd;
		bool toRemove;
		List<IPKKeybdResponder> respondersToRemove;
		bool toClear;
		#endregion

		#region Public Properties
		/// <summary>
		/// Whether or not the events are going to be dispatched.
		/// <remarks>Default value is true</remarks>
		/// </summary>
		public bool DispatchEvents { get; set; }
		#endregion

		#region Initialization
		private PKKeybdDispatcher()
		{
			this.DispatchEvents = true;

			this.keybdHandlers = new List<PKKeybdHandler>();
			this.handlersToAdd = new List<PKKeybdHandler>();
			this.respondersToRemove = new List<IPKKeybdResponder>();

			this.locked = false;
			this.toAdd = false;
			this.toRemove = false;
			this.toClear = false;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Adds a keyboard handler to the dispatcher's list.
		/// </summary>
		/// <param name="target">target keyboard object</param>
		/// <param name="priority">priority of handler</param>
		/// <param name="swallowesEvents">whether or not the event is swallowed</param>
		public void AddHandler(IPKKeybdResponder target, int priority, bool swallowesEvents)
		{
			Debug.Assert(target != null, "PKKeybdDispatcher.AddHandler: Argument cannot be null.");

			PKKeybdHandler handler = new PKKeybdHandler(target, priority, swallowesEvents);
			if (!this.locked)
			{
				this.ForceAddHandler(handler);
			}
			else
			{
				if (!RemoveResponderFromList(target, respondersToRemove))
				{
					this.handlersToAdd.Add(handler);
					this.toAdd = true;
				}
			}
		}

		/// <summary>
		/// Removes a keyboard handler.
		/// </summary>
		/// <param name="target">target keyboard object</param>
		public void RemoveHandler(IPKKeybdResponder target)
		{
			if (target == null)
			{
				return;
			}

			if (!this.locked)
			{
				this.ForceRemoveHandler(target);
			}
			else
			{
				if (!RemoveHanderFromList(target, handlersToAdd))
				{
					this.respondersToRemove.Add(target);
					this.toRemove = true;
				}
			}
		}

		/// <summary>
		/// Removes all keyboard handlers.
		/// </summary>
		public void ClearHandlers()
		{
			if (!this.locked)
			{
				this.ForceClearHandlers();
			}
			else
			{
				this.toClear = true;
			}
		}

		/// <summary>
		/// Changes the priority of a previously added keybd handler.
		/// The lower number, the higher priority.
		/// </summary>
		/// <param name="target">target object</param>
		/// <param name="priority">priority of handler</param>
		public void SetPriority(IPKKeybdResponder target, int priority)
		{
			Debug.Assert(target != null, "PKKeybdDispatcher.SetPriority: Argument cannot be null.");

			PKKeybdHandler handler = this.FindHandler(target);

			Debug.Assert(handler != null, "PKKeybdDispatcher.SetPriority: Cannot find specified keybd handler.");

			handler.Priority = priority;
			this.SortHandlers();
		}

		/// <summary>
		/// Key down event.
		/// </summary>
		/// <param name="keybd">keybd</param>
		public void KeyDown(PKKeybdEvent keybd)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(keybd, PKKeybdEventType.KeyDown);
			}
		}

		/// <summary>
		/// Key up event.
		/// </summary>
		/// <param name="keybd">keybd</param>
		public void KeyUp(PKKeybdEvent keybd)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(keybd, PKKeybdEventType.KeyUp);
			}
		}
		#endregion

		#region Private Methods
		private static bool RemoveResponderFromList(IPKKeybdResponder responder, List<IPKKeybdResponder> list)
		{
			foreach (IPKKeybdResponder item in list)
			{
				if (list == responder)
				{
					list.Remove(item);
					return true;
				}
			}
			return false;
		}

		private static bool RemoveHanderFromList(IPKKeybdResponder responder, List<PKKeybdHandler> list)
		{
			foreach (PKKeybdHandler item in list)
			{
				if (item.Target == responder)
				{
					list.Remove(item);
					return true;
				}
			}
			return false;
		}

		private void ForceAddHandler(PKKeybdHandler handler)
		{
			int index = 0;
			foreach (PKKeybdHandler item in this.keybdHandlers)
			{
				if (item.Priority < handler.Priority)
				{
					index++;
				}
				Debug.Assert(item.Target != handler.Target, "PKKeybdDispatcher.AddHandler: Handler already added to keybd dispatcher.");
			}
			this.keybdHandlers.Insert(index, handler);
		}

		private void ForceRemoveHandler(IPKKeybdResponder target)
		{
			foreach (PKKeybdHandler item in this.keybdHandlers)
			{
				if (item.Target == target)
				{
					this.keybdHandlers.Remove(item);
					break;
				}
			}
		}

		private void ForceClearHandlers()
		{
			this.keybdHandlers.Clear();
		}

		private PKKeybdHandler FindHandler(IPKKeybdResponder target)
		{
			foreach (PKKeybdHandler item in this.keybdHandlers)
			{
				if (item.Target == target)
				{
					return item;
				}
			}
			if (toAdd)
			{
				foreach (PKKeybdHandler item in this.handlersToAdd)
				{
					if (item.Target == target)
					{
						return item;
					}
				}
			}
			return null;
		}

		private void SortHandlers()
		{
			this.keybdHandlers.Sort(
				delegate(PKKeybdHandler item1, PKKeybdHandler item2)
				{
					return item1.Priority.CompareTo(item2.Priority);
				});
		}

		private void DispatchEvent(PKKeybdEvent keybd, PKKeybdEventType type)
		{
			Debug.Assert(type < PKKeybdEventType.KeyMax, "PKKeybdDispatcher.DispatchEvent: Invalid keyboard event.");

			if (keybd.Key == PKKeybdKey.Invalid)
			{
				return;
			}

			locked = true;

			if (keybdHandlers.Count > 0)
			{
				foreach (PKKeybdHandler handler in keybdHandlers)
				{
					bool claimed = false;
					if (type == PKKeybdEventType.KeyDown)
					{
						claimed = handler.Target.KeyDown(keybd);
						if (claimed)
						{
							handler.ClaimedEvents = keybd;
						}
					}
					else if (handler.ClaimedEvents == keybd)
					{
						claimed = true;
						if (type == PKKeybdEventType.KeyUp)
						{
							handler.Target.KeyUp(keybd);
							handler.ClaimedEvents = null;
						}
					}
					if (claimed && handler.SwallowesEvents)
					{
						// Then other handlers cannot receive this keybd event.
						break;
					}
				}
			}

			locked = false;
			if (toRemove)
			{
				toRemove = false;
				foreach (IPKKeybdResponder item in respondersToRemove)
				{
					this.ForceRemoveHandler(item);
				}
				respondersToRemove.Clear();
			}
			if (toAdd)
			{
				toAdd = false;
				foreach (PKKeybdHandler item in handlersToAdd)
				{
					this.ForceAddHandler(item);
				}
				handlersToAdd.Clear();
			}
			if (toClear)
			{
				toClear = false;
				this.ForceClearHandlers();
			}
		}
		#endregion
	}
}
